//
//  CQHomeController.swift
//  weibo
//
//  Created by chengqiang on 16/7/18.
//  Copyright © 2016年 chengqiangBiaodashi. All rights reserved.
//

import UIKit
import SVProgressHUD
import SVPullToRefresh
class CQHomeController: CQBaseController {
    
    
    //注册cell重用标示
    private let ReuseIdentfier = "ReuseIdentfier"
    
    var statuses: [CQstatus]? {
        didSet{
            self.tableView.reloadData()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
     
        
        //判断用户是否登录
        if !CQUserViewModel.shareduserAccountViewModel.userLogin{
            return
        }
        //显示FPS
        UIApplication.sharedApplication().keyWindow?.showInCenter()
        setNavigationbar()
        self.setupTableView()
        self.tableView.addSubview(pullDownToRefreshControl)
//    let access_token = CQUserViewModel.shareduserAccountViewModel.userAccount?.access_token
//        let urlString = "2/statuses/home_timeline.json"
//        let parameters=[
//        "access_token":access_token!
//        ]
//        
//        CQTool.sharedNetworking.GET(urlString, parameters: parameters, progress: nil, success: { (_, responseObject)->Void  in
//            print("返回微博数据\(responseObject)")
//            }) { (_, error)-> Void in
//                print("error:\(error)")
//        }
        
        self.pullDownToRefreshControl.refreshiongCallback = {()-> Void in
            self.loadNewStatus()
            
        }
        self.pullDownToRefreshControl.begainfreshing()
        
        //上啦加载更多 设置必报自动进入刷新状态
//        self.tableView.addInfiniteScrollingWithActionHandler { ()->Void in
//            self.loadMoreStatus()
//        }
    }
    
    private func setupTableView(){
        //注册cell
        self.tableView.registerClass(CQStatusCell.self, forCellReuseIdentifier: ReuseIdentfier)
        //设置默认行高根据cell里面的内容自适应
        self.tableView.estimatedRowHeight=200
        self.tableView.rowHeight=UITableViewAutomaticDimension
        self.tableView.separatorStyle=UITableViewCellSeparatorStyle.None
    }
    
    private func showTipLable(count:Int){
        
        let keys = self.tipLable.layer.animationKeys()
        if keys != nil {
            return
        }
        let message = count == 0 ? "没有新的微博数据":"加载了\(count)条微博数据"
        self.tipLable.text = message
        
        UIView.animateWithDuration(1, animations: {()->Void in
            self.tipLable.frame.origin.y = 44
        }){(_)->Void in
            UIView.animateWithDuration(1, delay: 0.75, options: UIViewAnimationOptions(rawValue:0), animations: {
                ()->Void in
                self.tipLable.frame.origin.y = -64
                }, completion: nil)
            
        }
    }
    
    
    //加载新内容
    private func loadNewStatus(){
        let since_id = self.statuses?.first?.id ?? 0
        
        CQStatuViewModel.sharedStatusViewModel.loadStatus(since_id, max_id: 0) { (error, statuModels)-> Void in
            
            //关闭刷新控件
            self.pullDownToRefreshControl.endfreshing()
            //判断是否有错误
            if error != nil{
                SVProgressHUD.showErrorWithStatus("获取模型数据失败")
                return
                
            }
            let count = statuModels?.count ?? 0
            if count == 0{
                return
            }
            if since_id>0{
                self.showTipLable(count)
            }
            if count == 0{
                print("没有加载到数据")
                return
            }
            
            //加载到了微博
            if since_id == 0{
                //第一次进入加载最新消息
                self.statuses = statuModels
                self.tableView.addInfiniteScrollingWithActionHandler { ()->Void in
                    self.loadMoreStatus()
                }
            }else{
                self.statuses = statuModels! + self.statuses!
                
            }
        }
    }
    
    
    //加载跟多以前的微博
    private func loadMoreStatus(){
        let max_id = self.statuses?.last?.id ?? 0
        CQStatuViewModel.sharedStatusViewModel.loadStatus(0, max_id: max_id) { (error, statuModels) ->Void in
            //关闭刷新控件避免与加载更多冲突
            self.tableView.infiniteScrollingView.stopAnimating()
            
            
            if error != nil{
                SVProgressHUD.showErrorWithStatus("上拉加载更多出错")
                return
            }
            let count = statuModels?.count ?? 0
            if count == 0 {
                SVProgressHUD.showInfoWithStatus("没有加载到更多数据")
                return
            }
            self.statuses = self.statuses! + statuModels!
            
        }
    }
    //设置航栏
    private func setNavigationbar(){
        self.navigationItem.leftBarButtonItem=UIBarButtonItem(imageName:"navigationbar_friendsearch")
        self.navigationItem.rightBarButtonItem=UIBarButtonItem(imageName:"navigationbar_pop")
        let screen_name = CQUserViewModel.shareduserAccountViewModel.userAccount?.screen_name ?? "小强哥"
        
        let titleBtn = CQHomeButton(title: screen_name)
        titleBtn.addTarget(self, action: "titleBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        self.navigationItem.titleView=titleBtn
        
    }
    @objc private func titleBtnClick(button:UIButton){
        button.selected = !button.selected
        
        let transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI-0.0001)):CGAffineTransformIdentity
        UIView.animateWithDuration(DefaultAnimtionDuration) { 
            ()->Void in
            button.imageView?.transform=transform
        }
    }
    
    
    //MARK:-懒加载下拉刷新控件
    private lazy var pullDownToRefreshControl:CQPullDownToRefreshController = CQPullDownToRefreshController()
    
    
    private lazy var tipLable:UILabel = {
        let lable = UILabel()
        let tipLableHeight:CGFloat = 44
        lable.backgroundColor = UIColor.orangeColor()
        lable.textAlignment = NSTextAlignment.Center
        lable.textColor = UIColor.whiteColor()
        lable.font = UIFont.systemFontOfSize(18)
        lable.frame = CGRect(x: 0, y: -20-tipLableHeight, width: UIScreen.width(), height: tipLableHeight)
        
        //添加到导航栏上
        self.navigationController?.navigationBar.insertSubview(lable,atIndex:0)
        return lable
    }()
}



//MARK:- 实现数据源方法
extension CQHomeController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentfier, forIndexPath: indexPath) as! CQStatusCell
        let staus  = self.statuses![indexPath.row]
        cell.status=staus
        return cell
        
    }
    
    //设置点击cell后不高亮
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
}
